package com.dsteiner.widgets.client.controller;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import com.dsteiner.widgets.client.Widgets.IAbsolutePanel;
import com.dsteiner.widgets.client.Widgets.IImage;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.dsteiner.widgets.client.model.PrintableImageModel;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Image;

public class PrintableImageController {

	private IImage printImage;
	private PrintableImageModel printableImageModel;
	private Image image;
	private IAbsolutePanel absolutePanel;

	public void registerImage(Image image) {
		this.image = image;
	}

	public void registerPrintableImage(ILazyWidget printableImage) {
		printableImage.addWidgetListener(new WidgetListenerAdapter(){
			@Override
			public void onAttach(IWidget widget) {
				updateImage();
				updatePrintImageUrl();
			}
		});
	}

	public void registerPrintableImageModel(PrintableImageModel printableImageModel) {
		this.printableImageModel = printableImageModel;
		printableImageModel.addPropertyChangeListener(new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				if("image".equals(evt.getPropertyName())){
					updateImage();
				}
				else if("url".equals(evt.getPropertyName())){
					updatePrintImageUrl();
				}
			}
		});
	}

	public void registerPrintImage(IImage printImage) {
		this.printImage = printImage;
	}

	private void updateImage() {
		AbstractImagePrototype abstractImagePrototype = printableImageModel.getImage();
		if(abstractImagePrototype == null)
			return;
		abstractImagePrototype.applyTo(image);
    	int height = image.getHeight();
    	int width = image.getWidth();
    	absolutePanel.setPixelSize(width, height);
	}

	private void updatePrintImageUrl() {
		String url = printableImageModel.getUrl();
		printImage.setVisible(url != null);
		if(url != null)
			printImage.setUrl(url);
	}

	public void registerAbsolutePanel(IAbsolutePanel absolutePanel) {
		this.absolutePanel = absolutePanel;
	}

}
